package com.smartum.mpr.services;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.smartum.mpr.business.PurchaseBusiness;
import com.smartum.mpr.business.UserBusiness;
import com.smartum.mpr.exception.NotExistsUserException;
import com.smartum.mpr.model.User;

@Controller
@RequestMapping("/purchase")
public class PurchaseService extends BaseService<User> {

	@Autowired
	private PurchaseBusiness purchaseBusiness;

	@RequestMapping(method = RequestMethod.POST, value = "/item/add")
	public ResponseEntity<String> addItemPurchase(@RequestBody String json) {
		try {

			String request = extractRequestStringData(json);
			ObjectMapper mapper = getTargetParser().getMapper();
			JsonNode requestNode = mapper.readTree(request);

			long categoryId = requestNode.get("category_id").asLong();
			long receiptId = requestNode.get("receipt_id").asLong();
			String transactionReceipt = requestNode.get("transaction_receipt").asText();
			
			
			String token = extractTokenStringData(json);
			purchaseBusiness.saveItemPurchase(token, categoryId, receiptId, transactionReceipt);

			return new ResponseEntity<String>(HttpStatus.OK);
		} catch (Exception e) {
			return handleException(e);
		}
	}

	@RequestMapping(method = RequestMethod.POST, value = "job/add")
	public ResponseEntity<String> addJobPurchase(@RequestBody String json) {
		try {

			String request = extractRequestStringData(json);
			ObjectMapper mapper = getTargetParser().getMapper();
			JsonNode requestNode = mapper.readTree(request);

			long categoryId = requestNode.get("category_id").asLong();
			long receiptId = requestNode.get("receipt_id").asLong();
			String transactionReceipt = requestNode.get("transaction_receipt").asText();
			
			
			String token = extractTokenStringData(json);
			purchaseBusiness.saveJobPurchase(token, categoryId, receiptId, transactionReceipt);

			return new ResponseEntity<String>(HttpStatus.OK);
		} catch (Exception e) {
			return handleException(e);
		}
	}
	
	@Override
	protected Class<User> getEntityClass() {
		return User.class;
	}

}
